package com.yootk.main;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.WritableResource;

import java.io.File;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

/**
 * 资源读取与NIO支持
 */
public class Demo04_NIO {
    public static void main(String[] args) throws Exception {
//        test1();
        test2();
    }

    /**
     * WritableByteChannel，写入文件资源
     */
    public static void test1() throws Exception {
        String path = "F:" + File.separator + "muyan" + File.separator + "message.txt";
        File file = new File(path);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        if (file.exists()) {
            file.delete();
        }
        file.createNewFile();
        WritableResource resource = new FileSystemResource(file);
        WritableByteChannel channel = resource.writableChannel();   // 写入通道
        byte[] data = "沐言科技：www.yootk.com".getBytes();
        ByteBuffer buffer = ByteBuffer.wrap(data);  // 定义字节缓冲区
        channel.write(buffer);  // 数据写入
        channel.close();
    }

    /**
     * ReadableByteChannel，读取文件资源
     */
    public static void test2() throws Exception {
        String path = "F:" + File.separator + "muyan" + File.separator + "message.txt";
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        Resource resource = new FileSystemResource(file);
        ReadableByteChannel channel = resource.readableChannel();   // 读取通道
        ByteBuffer buffer = ByteBuffer.allocate(30);    // 分配字节缓冲区
        channel.read(buffer);   // 将数据读取到缓冲区之中
        buffer.flip();
        byte[] data = new byte[30];
        int foot = 0;
        while (buffer.hasRemaining()) {
            data[foot++] = buffer.get();
        }
        System.err.println(new String(data, 0, foot));
        channel.close();
    }
}
